package com.common;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import com.common.user.domain.Permission;
import com.common.user.domain.Role;
import com.common.user.domain.User;
import com.common.user.properties.InitProperties;
import com.common.user.repository.PermissionRepository;
import com.common.user.repository.RoleRepository;
import com.common.user.service.UserService;
import com.common.weapp.bean.WeMappingJackson2HttpMessageConverter;


@SpringBootApplication
public class GidCommonServiceApplication {

	public static void main(String[] args) throws Exception {
		
		ApplicationContext context = SpringApplication.run(GidCommonServiceApplication.class, args);
		
		InitProperties initProperties = context.getBean(InitProperties.class);
		
		if(initProperties.isEnable()) {
			UserService userService = context.getBean(UserService.class);
			RoleRepository roleRepository = context.getBean(RoleRepository.class);
			PermissionRepository permissionRepository = context.getBean(PermissionRepository.class);
			
			User user = initProperties.getUser();
			
			if(userService.findByUsername(user.getUsername()) == null) { //The user not exist.
				
				Permission permission_permission = new Permission();
				permission_permission.setName("Permission manage");
				permission_permission.setUrl("/permissions/**");
				
				Permission role_permission = new Permission();
				role_permission.setName("Role manage");
				role_permission.setUrl("/roles/**");
				
				Permission user_permission = new Permission();
				user_permission.setName("User manage");
				user_permission.setUrl("/users/**");
				
				permissionRepository.save(Arrays.asList(permission_permission, role_permission, user_permission));
				 
				Role role = new Role();
				role.setName(user.getUsername());
				role.getPermissions().addAll(Arrays.asList(permission_permission, role_permission, user_permission));
				roleRepository.save(role);

				user.getRoles().add(role);
				userService.register(user);			
			}
		}	
	}
	
	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		RestTemplate restTemplate = builder.build();		
		restTemplate.getMessageConverters().add(new WeMappingJackson2HttpMessageConverter());
		
		return restTemplate;
	}
}
